package lhb.test.SC.common.exception;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.fasterxml.jackson.databind.ObjectMapper;

import io.swagger.annotations.ApiOperation;
import lhb.test.SC.common.model.ReturnMessage;

public class HandlerExceptionResolver extends SimpleMappingExceptionResolver {

	@Override
	public int getOrder() {
		return Integer.MAX_VALUE;
	}
	
	@Autowired
	ObjectMapper mapper;
	
	boolean hasApiAnnotation = true;
	public HandlerExceptionResolver(){
		try {
			Class.forName("io.swagger.annotations.ApiOperation");
		} catch (Exception e) {
			hasApiAnnotation = false;
		}
	}
	
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		boolean returnView = true;
		if (request.getHeader("accept") == null || request.getHeader("accept").indexOf("application/json") > -1
				|| (request.getHeader("X-Requested-With") != null
						&& request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1)
				|| (response.getContentType() != null && response.getContentType().indexOf("application/json") > -1)) {
			returnView = false;
		}
		if (returnView) {
			String viewName = null;
			return getModelAndView(viewName, ex, request);
		} else {
			PrintWriter writer = null;
			try {
				response.setContentType("application/json;charset=UTF-8");
				response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				ReturnMessage msg = null;
				if(ex instanceof BusinessException){
					msg = new ReturnMessage(ex.getMessage());
				}else{
					if(hasApiAnnotation){
						if(handler instanceof HandlerMethod){
							HandlerMethod hm = (HandlerMethod) handler;
							Method method = hm.getMethod();
							ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
							if(apiOperation!=null){
								msg = new ReturnMessage(apiOperation.value()+" 失败，请重试");
							}
						}
					}
					if(msg==null){
						msg = new ReturnMessage("访问异常，请联系管理员");
					}
				}
				String result = mapper.writeValueAsString(msg);
				writer = response.getWriter();
				writer.write(result);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if(writer!=null)writer.close();
				} catch (Exception e2) {
				}
			}
		}
		return null;
	}

}